<template>
  <div>
    <el-popover
      popper-class="my-setting"
      :placement="position"
      width="60"
      trigger="hover"
    >
      <ul class="setting-list">
        <li>
          <a href="javascript:void(0);" @click="handleCommand('changePassword')"
            ><i class="fa fa-unlock-alt"></i>修改密码</a
          >
        </li>
        <li>
          <a href="javascript:void(0);" @click="handleCommand('exit')"
            ><i class="fa fa-sign-out"></i>退出登录</a
          >
        </li>
      </ul>
      <span
        slot="reference"
        class="pan-user-info"
        :style="position === 'bottom' ? 'padding: 0' : ''"
      >
        <div class="touxiang"></div>
        <div class="name">{{ username }}</div>
        <i class="el-icon-setting el-icon--right" />
      </span>
    </el-popover>
    <el-dialog
      title="修改密码"
      :visible.sync="changePasswordDialogVisible"
      @opened="focusPasswordInput"
      @closed="resetChangePasswordForm"
      width="450px"
      :append-to-body="true"
      :modal-append-to-body="false"
      :center="true"
    >
      <div>
        <el-form
          label-width="100px"
          :rules="changePasswordRules"
          ref="changePasswordForm"
          :model="changePasswordForm"
          status-icon
          @submit.native.prevent
        >
          <el-form-item label="旧密码" prop="password">
            <el-input
              type="password"
              show-password
              ref="password"
              @keyup.enter.native="doChangePassword"
              v-model="changePasswordForm.password"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              type="password"
              show-password
              @keyup.enter.native="doChangePassword"
              v-model="changePasswordForm.newPassword"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="reNewPassword">
            <el-input
              type="password"
              show-password
              @keyup.enter.native="doChangePassword"
              v-model="changePasswordForm.reNewPassword"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changePasswordDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="doChangePassword" :loading="loading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import userService from '../../api/user'
import { clearToken } from '../../utils/cookie'
import { mapGetters, mapMutations } from 'vuex'
import { encrypt } from '../../utils/jsencrypt'
import { checkPassword } from '../../utils/pwd'

export default {
  name: 'PanUserInfo',
  props: {
    position: {
      type: String,
      default: 'right-start',
    },
  },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.changePasswordForm.newPassword !== value) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    const validatePsw = (rule, value, callback) => {
      if (!this.pwdCheck(value)) {
        callback(new Error('密码需要包含小写字母、大写字母、数字、特殊字符'))
      } else {
        callback()
      }
    }
    return {
      changePasswordDialogVisible: false,
      changePasswordForm: {
        password: '',
        newPassword: '',
        reNewPassword: '',
      },
      loading: false,
      changePasswordRules: {
        password: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '长度在 6 到 20 个字符',
            trigger: 'blur',
          },
          { required: true, validator: validatePsw, trigger: 'blur' },
        ],
        reNewPassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { required: true, validator: equalToPassword, trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    ...mapMutations({
      clearFile: 'file/clear',
      clearBreadCrumb: 'breadcrumb/clear',
      clearNavBar: 'navbar/clear',
      clearUser: 'user/clear',
      setParentId: 'file/setFileParentId',
      setDefaultParentId: 'file/setFileDefaultParentId',
      setDefaultParentFilename: 'file/setDefaultParentFilename',
      setUsername: 'user/setUsername',
    }),
    handleCommand(command) {
      if (command === 'changePassword') {
        this.changePasswordDialogVisible = true
      } else if (command === 'exit') {
        this.exit()
      }
    },
    doChangePassword() {
      let _this = this
      _this.$refs.changePasswordForm.validate((valid) => {
        if (valid) {
          _this.loading = true
          userService.changePassword(
            {
              password: encrypt(_this.changePasswordForm.password),
              newPassword: encrypt(_this.changePasswordForm.newPassword),
            },
            () => {
              _this.loading = false
              _this.changePasswordDialogVisible = false
              _this.$notify({
                title: '成功',
                message: '密码修改成功,即将跳转至登录页面',
                type: 'success',
              })
              setTimeout(() => _this.goLogin(), 1000)
            },
            (res) => {
              _this.$message.error(res.message)
              _this.loading = false
            }
          )
        }
      })
    },
    exit() {
      let _this = this
      if (_this.$listeners['exit']) {
        _this.$emit('exit')
      } else {
        _this
          .$confirm('确定要退出登录吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(() => {
            userService.exit(
              () => {
                _this.goLogin()
              },
              (res) => {
                _this.$message.error(res.message)
              }
            )
          })
      }
    },
    goLogin() {
      clearToken()
      this.clearFile()
      this.clearBreadCrumb()
      this.clearNavBar()
      this.clearUser()
      window.location.reload()
    },
    focusPasswordInput() {
      this.$refs.password.focus()
    },
    resetChangePasswordForm() {
      this.$refs.changePasswordForm.resetFields()
    },
    initUserInfoIfNecessary() {
      let _this = this
      if (!_this.username) {
        userService.info(
          (res) => {
            _this.setParentId(res.data.rootFileId)
            _this.setDefaultParentId(res.data.rootFileId)
            _this.setDefaultParentFilename(res.data.rootFilename)
            _this.setUsername(res.data.username)
          },
          (res) => {
            _this.$message.error(res.message)
          }
        )
      }
    },
    pwdCheck() {
      if (
        this.changePasswordForm.newPassword != null &&
        this.changePasswordForm.newPassword != ''
      ) {
        if (checkPassword(this.changePasswordForm.newPassword)) {
          return true
        } else {
          this.changePasswordForm.newPassword = ''
          return false
        }
      }
    },
  },
  computed: {
    ...mapGetters(['username']),
  },
  mounted() {
    this.initUserInfoIfNecessary()
  },
  watch: {},
}
</script>

<style lang="scss" scoped>
.pan-user-info {
  color: #409eff;
  display: flex;
  align-items: center;

  height: 60px;
  line-height: 60px;
  padding: 0 25px;
  cursor: pointer;
  border-top: 1px solid #eee;
  font-size: 14px;
  .touxiang {
    display: block;
    width: 30px;
    height: 30px;
    background-image: url('@/assets/imgs/touxiang.png');
    border-radius: 100%;
    background-size: cover;
    margin-right: 10px;
  }
  .name {
    margin-right: 10px;
  }
  i {
    margin-left: auto;
  }
}
.setting-list {
  li {
    a {
      line-height: 3em;
      display: flex;
      align-items: center;
      color: #636d7e;
      i {
        width: 1em;
        text-align: center;
        padding: 0 10px;
      }
      &:hover {
        opacity: 0.6;
      }
    }
    &:first-child {
      border-bottom: 1px solid #eee;
    }
  }
}
</style>
<style>
.el-popover.my-setting {
  min-width: 100px;
  padding: 0;
}
</style>
